package jys.test.yddata.utils;

import android.annotation.SuppressLint;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class VerifyManager extends ClientManager {
    private PropertiesUtil projectProp;
    /**
     * 初始化服务
     * @param appCompatActivity APP界面
     * @param response          请求处理状态回调方法
     * @param url               服务器地址
     */
    protected VerifyManager(AppCompatActivity appCompatActivity, Consumer<Boolean> response, String url) {
        super(appCompatActivity, response, url);

        try {
            projectProp = PropertiesUtil.buildFromDisk(app, "project");
        } catch (IOException e) {
            e.printStackTrace();
            seriousError("配置加载出错，Exp ["+e.getMessage()+"]");
        }

        requestCallback = new Callback() {     // 请求回调
            @Override
            public void onFailure(@NotNull Call call, IOException e) {
                remind2User(false, "请求失败，Exp ["+e.getMessage()+"]");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, Response response) throws IOException {
                if (response.code() != 200) {
                    remind2User(false, "请求失败，CODE ["+response.code()+"]");
                } else if (response.body() == null) {
                    remind2User(false, "请求失败，服务器信息 [null]");
                } else {
                    String setting = response.body().string();
                    if (setting.contains("# server")) {
                        remind2User(true, setting.replace("<br>", "\n"));
                    } else {
                        remind2User(false, "请求失败，服务器信息 ["+setting+"]");
                    }
                }
            }
        };
    }

    @Override
    protected void remind2User(boolean isOK, String message) {
        if (isOK) {
            try {
                projectProp.load(new InputStreamReader(new ByteArrayInputStream(message.getBytes()), StandardCharsets.UTF_8));
                projectProp.storeToUser();
                app.runOnUiThread(()-> responseFunc.accept(isOK));
            } catch (IOException e) {
                remind2User(false, "保存失败，Exp ["+e.getMessage()+"]");
                e.printStackTrace();
            }
        } else
            app.runOnUiThread(()->{
                Toast.makeText(app, message, Toast.LENGTH_SHORT).show();
                responseFunc.accept(isOK);
            });
    }

    public void sendVerify(String verify) {
        if (!checkNetworkOK()) return;

        Request request = new Request.Builder()
                .url(socketUrl+verify)
                .get()
                .build();

        client.newCall(request).enqueue(requestCallback);
    }

    private void seriousError(String message) {
        new AlertDialog.Builder(app)
                .setTitle("错误")
                .setMessage(message)
                .setPositiveButton("退出", (dialog, which)-> app.finish())
                .show();
    }

    public static class Builder {
        private boolean inited = false;
        private VerifyManager clientManager;

        public VerifyManager.Builder init(AppCompatActivity appCompatActivity, Consumer<Boolean> response, String url) {
            inited = true;
            clientManager = new VerifyManager(appCompatActivity, response, url);
            return this;
        }

        @SuppressLint("Assert")
        public VerifyManager build() {
            assert inited;
            return clientManager;
        }
    }
}
